package com.example.esdemo.services.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.core.libs.AppException;
import com.example.core.utils.Beans;
import com.example.esdemo.constants.RabbitConstant;
import com.example.esdemo.entities.Post;
import com.example.esdemo.es.entities.EsPost;
import com.example.esdemo.es.services.EsPostService;
import com.example.esdemo.forms.PostCreateForm;
import com.example.esdemo.forms.PostDeleteForm;
import com.example.esdemo.forms.PostSearchForm;
import com.example.esdemo.mapper.PostMapper;
import com.example.esdemo.rabbitmq.ESMqMessage;
import com.example.esdemo.services.IPostService;
import com.example.esdemo.utils.PageHelper;
import com.example.esdemo.vo.PostVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Cary
 * @date 2022/6/21
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private EsPostService esPostService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PostCreateForm form) {
        Post post = Beans.copy(form, Post.class);
        post.setCreateTime(new Date());
        save(post);

        EsPost esPost = Beans.copy(post, EsPost.class);
        //使用rabbitmq同步到elasticsearch搜索引擎服务器
        rabbitmqSend(esPost, ESMqMessage.CREATE_OR_UPDATE);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(PostDeleteForm form) {
        Post post = getById(form.getId());
        if (Beans.isNull(post)) {
            throw new AppException("无效数据");
        }
        removeById(post.getId());
        EsPost esPost = Beans.copy(post, EsPost.class);
        rabbitmqSend(esPost, ESMqMessage.REMOVE);
    }

    @Override
    public List<PostVo> dbList() {
        return Beans.copyList(list(), PostVo.class);
    }

    @Override
    public List<PostVo> esList() {
        return Beans.copyList(esPostService.list(), PostVo.class);
    }

    @Override
    public IPage<PostVo> search(PostSearchForm form) {
        IPage<EsPost> esPostPage = esPostService.search(form);
        return PageHelper.coverTo(esPostPage, PostVo.class);
    }

    /**
     * 发送消息
     *
     * @param post
     * @param type
     */
    private void rabbitmqSend(EsPost post, String type) {
        rabbitTemplate.convertAndSend(RabbitConstant.ES_EXCHAGE, RabbitConstant.ES_ROUTING_KEY,
                new ESMqMessage(post, type));
    }
}
